Magic squares are useful arrays to control compositional structures. They were used by Bach to determine the number of bars within sections and passages.
A useful magic square is defined as a 3x3 array:
(setq magic-square3
(build-array
'((4 9 2)
(3 5 7)
(8 1 6))))
The first 9 numbers can be arranged in a magic square so that all rows, columns and both diagonals have the same sum, 15. This can be done in essentially only one way, all solutions being related by reflections and rotations to each other.
This magic cube was also known by the ancient Chinese. The pattern has beautiful properties. The number 5, halfway between 1 and 9, naturally occupies the middle cell.
All four lines through the central 5 are in arithmetical progression, with differences 1, 2, 3, 4 rotating anti-clockwise from 6-5-4 to 9-5-1. The sum of the squares of the first and third colums are equal: 4^2+3^2+8^2=2^2+7^2 +6^2=89. The middle column gives 9^2+5^2+1^2=107=89+18. The squares of the numbers in the rows sum to 101, 83 and 101, and 101-83=18.
There are 8 ways in which the magic total 15 can be made by adding 3 of the integers 1 to 9. Each of these 8 ways occurs once in the square.
Another useful magic square is a 4x4 array:
(setq magic-square4
(build-array
'((12 13 1 8)
(6 3 15 10)
(7 2 14 11)
(9 16 4 5))))
To return the magic square elements use pick-array.
(pick-array 0 0 4 magic-square4 :right)
--> (12 13 1 8)
(pick-array 0 2 4 magic-square4 :right)
--> (1 8 12 13)
(pick-array 1 0 4 magic-square4 :right)
--> (6 3 15 10)
(pick-array 1 0 4 magic-square4 :down)
--> (6 7 9 12)
(pick-array 0 0 4 magic-square4 :diagonal-down)
--> (12 3 14 5)
(pick-array 3 0 4 magic-square4 :diagonal-up)
The sum of the cubes of the numbers along each diagonal are equal, to 4624=68^2. The sum of the squares of the numbers in the 1st and 4th rows are equal. The same property is shared in the 2nd and 3rd rows and by 1st and 4th columns and the 2nd and 3rn colums.